<?php
// src/Inter/ArticleBundle/Controller/AdminController.php;
namespace Inter\ArticleBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Symfony\Component\HttpFoundation\Response;
use Inter\ArticleBundle\Form\Type\RegistrationType;
use Inter\ArticleBundle\Form\Model\Registration;
use Symfony\Component\HttpFoundation\JsonResponse;
use Inter\ArticleBundle\Entity\Article;
use Inter\ArticleBundle\Form\Type\ArticleType;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\VarDumper\VarDumper;


class AdminController extends Controller 
{
    

    public function registerAction()
    {
    	if (false === $this->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY')) {
    		throw new AccessDeniedException();
    	}
        
    	$user = $this->get('security.context')->getToken()->getUser();
    	$roles = ($user->getRoles());
    	$userName = $user->getUserName();
    	
        $registration = new Registration();
        $form = $this->createForm(new RegistrationType(), $registration, array(
            'action' => $this->generateUrl('inter_article_admin_create'),
        ));
        
        
		
        return $this->render(
            'InterArticleBundle:Admin:register.html.twig',
            array('form' => $form->createView(),
            		'roles'=>$roles[0],
            		'userName' => $userName,
            )
        );
    }
    
    public function createAction(Request $request)
    {
    	if (false === $this->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY')) {
    		throw new AccessDeniedException();
    	}
    	
    	$user = $this->get('security.context')->getToken()->getUser();
    	$roles = ($user->getRoles());
    	$userName = $user->getUserName();
    	
        $em = $this->getDoctrine()->getManager();    
        $form = $this->createForm(new RegistrationType(), new Registration());    
        $form->bind($request);
        
        if ($form->isValid()) {
            
        	//$error =  $form->getErrors();
        	//print_r($error);
        	//exit;
        	
        	$registration = $form->getData();
            $user = $registration->getUser();
            
            //$user->setSalt(md5(uniqid()));
            $user->setRoles('ROLE_USER');
            
            $user->setSalt(md5(uniqid()));
            $encoder = $this->container->get('security.encoder_factory')->getEncoder($user);
            $user->setPassword($encoder->encodePassword($user->getPassword(), $user->getSalt()));
            
            /*$encoded = $this->container->get('security.password_encoder')
                            ->encodePassword($user, $user->getPassword());
                            
            $user->setPassword($encoded);
            */
            $em->persist($user);
            
            $em->flush();
            
            //print_r($registration->getUser());
            //exit;
            
            //$rs=  "user created!!";
            //return new Response($rs);
            $url = $this->generateUrl("inter_article_admin_list_user");
            return $this->redirect($url);
        }
    
        return $this->render(
            'InterArticleBundle:Admin:register.html.twig',
            array('form' => $form->createView(),
            		'roles'=>$roles[0],
            		'userName' => $userName,
            )
        );
    }
    
    public function listUserAction() {
    	
    	if (false === $this->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY')) {
    		throw new AccessDeniedException();
    	}
    	$user = $this->get('security.context')->getToken()->getUser();
    	$roles = ($user->getRoles());
    	$userName = $user->getUserName();
    	
        $em = $this->getDoctrine()->getManager();
        $users = $em->getRepository('InterArticleBundle:User')
                    ->getAllUser();
        
                        
        //print_r($users);
        //exit;
        
        return $this->render('InterArticleBundle:Admin:listUser.html.twig',
        				 array('users'=>$users,
        				 		'roles'=>$roles[0],	
        				 		'userName' => $userName,
        				 ));
    }
    
    public function changeUserRoleAction(Request $request){
    	if ($request->isXMLHttpRequest()) {         
    		
    		$id = $request->request->get('id');
    		$role = ($request->request->get('r') == 1) ? 'ROLE_USER' : 'ROLE_ADMIN';
    		
    		
    		$em = $this->getDoctrine()->getManager();
		    $user = $em->getRepository('InterArticleBundle:User')->find($id);
		
		    if (!$user) {
		    	return new JsonResponse(array('id' => $id, 'role'=> $role, 'result' => '1'));
		    }

    		$user->setRoles($role);
    		$em->flush();
    		$return=json_encode(array('id' => $id, 'role'=> $role, 'result' => '1'));//jscon encode the array
    		return new Response($return,200,array('Content-Type'=>'application/json'));
        	//return new JsonResponse(array('id' => $id, 'role'=> $role, 'result' => '1'));
    	}
    	return new Response('This is not ajax!', 400);
    	
    }
    
    public function editUserAction(){
        return $this->render('InterArticleBundle:Admin:editUser.html.twig');
    }
    
    public function activeUserAction(Request $request){
    	if (false === $this->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY')) {
    		throw new AccessDeniedException();
    	}
    	$user = $this->get('security.context')->getToken()->getUser();
    	$roles = ($user->getRoles());
    	$userName = $user->getUserName();
    	
    	$service = $this->container->get('inter_article.service.common');
    	$pagination = $service->getDemo($request, $user);
    	
    	
    	return $this->render('InterArticleBundle:Admin:listArticle.html.twig',
    	 		array('pagination' => $pagination,
    	 				'roles' =>$roles[0],
    	 				'userName' => $userName,));
    }
    
    public function addArticleAction(){    	
    	
    	if (false === $this->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY')) {
    		throw new AccessDeniedException();
    	}
    	$user = $this->get('security.context')->getToken()->getUser();
    	$roles = ($user->getRoles());
    	$userName = $user->getUserName();
    	
    	/** @var $articleManager \Inter\ArticleBundle\Model\ArticleManagerInterface */
    	$articleManager = $this->get('inter_article.article_manager');
    	$article = $articleManager->createArticle();    	
    	$article->setAuthor($user);    	
    	
    	$form = $this->createForm(new ArticleType(),$article);
    	$form->setData($article);
    	    	
    	$request = $this->getRequest();
    	if ($request->getMethod() == 'POST') {
    		$form->bind($request);
    	
    		if ($form->isValid()) { 			
    			$articleManager->updateArticle($article);
    			
    			$url = $this->generateUrl("inter_article_admin_list_article");
    			return $this->redirect($url);
    		}
    	}
    	
    	return $this->render('InterArticleBundle:Admin:addArticle.html.twig',
    	array('form' => $form->createView(),
    			'roles' => $roles[0],
    			'userName' => $userName,
    	));
    }
    
    public function listArticleAction(Request $request) {
    	if (false === $this->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY')) {
    		throw new AccessDeniedException();
    	}
    	
    	$user = $this->get('security.context')->getToken()->getUser();    	
    	$roles = ($user->getRoles());
    	$userName = $user->getUserName();
    	$userId = $user->getId();
    	
    	//var_dump($userId);
    	//exit;
    	$em = $this->getDoctrine()
    	->getEntityManager();
    	
    	$result = $em->createQueryBuilder()
    		->select('a')
    		->from('InterArticleBundle:Article',  'a')
    		->where('a.author = :userID')
    		->addOrderBy('a.createdat', 'DESC')
    		->setParameter('userID', $userId)
    		->getQuery()
    		->getResult()
    		;
		
    	$cache_key = 'article_cache_admin_listarticle';
    	$cache = $this->get('liip_doctrine_cache.ns.interarticle');
    	 
    	if (false === ($cached_data = $cache->fetch($cache_key))) {
    		$cached_data = $result;
    		$cache->save($cache_key, $cached_data, 3600);//TTL 1h
    	}
    	
    	
    	$paginator  = $this->get('knp_paginator');
    	$pagination = $paginator->paginate(
    			$result,
    			$request->query->get('page', 1)/*page number*/,
    			5/*limit per page*/
    	);
    	
        return $this->render('InterArticleBundle:Admin:listArticle.html.twig', 
        						array('pagination' => $pagination,
        								'roles' =>$roles[0],
        								'userName' => $userName,
        						));
    }
    
    public function editArticleAction(Request $request){
    	
    	if (false === $this->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY')) {
    		throw new AccessDeniedException();
    	}
    	$user = $this->get('security.context')->getToken()->getUser();
    	$roles = ($user->getRoles());
    	$userName = $user->getUserName();
    	
    	$id = $request->query->get('id', 1);
    	$em = $this->getDoctrine()->getManager();
    	$article = $em->getRepository('InterArticleBundle:Article')->find($id);
    	
    	if (!$article) {
    		throw $this->createNotFoundException('Unable to find Article post.');
    	}
    	
    	if($article->getAuthor()->getId() != $user->getId()){
    		throw new AccessDeniedException();
    	}
    	
    	$form = $this->createForm(new ArticleType(), $article);
    	
    	$request = $this->getRequest();
    	if ($request->getMethod() == 'POST') {
    		$form->bind($request);
    		 
    		if ($form->isValid()) {
    			$em->flush();
    			 
    			$url = $this->generateUrl("inter_article_admin_list_article");
    			return $this->redirect($url);
    		}
    	}
    	 
    	return $this->render('InterArticleBundle:Admin:editArticle.html.twig',
    			array('form' => $form->createView(),
    					'id' => $id,
    					'roles' => $roles[0],
    					'userName' => $userName,
    			));
    }
    
    public function deleteArticleAction(Request $request)
    {	
    	if (false === $this->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY')) {
    		throw new AccessDeniedException();
    	}
    	$id = $request->query->get('id', 1);
    	$em = $this->getDoctrine()->getManager();
    	$article = $em->getRepository('InterArticleBundle:Article')->find($id);
    	$em->remove($article);
    	$em->flush();
    	$url = $this->generateUrl("inter_article_admin_list_article");
    	return $this->redirect($url);
    }
    
    public function viewArticleAction($id){
    	if (false === $this->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY')) {
    		throw new AccessDeniedException();
    	}
    	$user = $this->get('security.context')->getToken()->getUser();
    	$roles = ($user->getRoles());
    	$userName = $user->getUserName();
    	$userId = $user->getId();
    	
    	$em = $this->getDoctrine()->getManager();
    	$article = $em->getRepository('InterArticleBundle:Article')->find($id);
    	 
    	if (!$article) {
    		throw new AccessDeniedException();
    	}
    	
    	$author = $article->getAuthor()->getId();
    	
    	if($author != $userId) {
    		throw new AccessDeniedException();
    	}
    	
        return $this->render('InterArticleBundle:Admin:viewArticle.html.twig', 
        		array(
        				'article' => $article,        				
        				'roles' => $roles[0],
        				'userName' => $userName,
        		));
    }
    
    public function activeArticleAction(){
        $rs=  "result Article";
        return new Response($rs);
        
        
    }
    
    public function loginAction(){
    	
    	$request = $this->getRequest();
    	$session = $request->getSession();
    	
    	// get the login error if there is one
    	if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
    		$error = $request->attributes->get(
    				SecurityContext::AUTHENTICATION_ERROR
    		);
    	} else {
    		$error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
    		$session->remove(SecurityContext::AUTHENTICATION_ERROR);
    	}
    	
    	return $this->render(
    			'InterArticleBundle:Admin:login.html.twig',
    			array(
    					// last username entered by the user
    					'last_username' => $session->get(SecurityContext::LAST_USERNAME),
    					'error'         => $error,
    			)
    	);
    	
    }
    
    public function dumpStringAction()
    {
    	return $this->render('InterArticleBundle:Admin:dumpString.html.twig', array());
    }
    
    public function dashBoardAction(){
    	if (false === $this->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY')) {
    		throw new AccessDeniedException();
    	}
    	
    	$user = $this->get('security.context')->getToken()->getUser();
    	$roles = ($user->getRoles());
    	if($roles[0] == 'ROLE_ADMIN')
    	{
    		$url = $this->generateUrl("inter_article_admin_list_user");
    		return $this->redirect($url);
    	} else {
    		$url = $this->generateUrl("inter_article_admin_list_article");
    		return $this->redirect($url);
    	}
    }
    
    public function articleListPagingWithAjaxAction(Request $request)
    {
    	if ($request->isXMLHttpRequest()) {
    	
    		if (false === $this->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY')) {
    			throw new AccessDeniedException();
    		}
    		$user = $this->get('security.context')->getToken()->getUser();    		
    		$userId = $user->getId();
    		 
    		//var_dump($userId);
    		//exit;
    		$em = $this->getDoctrine()
    		->getEntityManager();
    		 
    		$result = $em->createQueryBuilder()
    		->select('a')
    		->from('InterArticleBundle:Article',  'a')
    		->where('a.author = :userID')
    		->addOrderBy('a.createdat', 'DESC')
    		->setParameter('userID', $userId)
    		->getQuery()
    		->getResult()
    		;
    		
    		$cache_key = 'article_cache_admin_listarticle';
    		$cache = $this->get('liip_doctrine_cache.ns.interarticle');
    		
    		if (false === ($cached_data = $cache->fetch($cache_key))) {
    			$cached_data = $result;
    			$cache->save($cache_key, $cached_data, 3600);//TTL 1h
    		}
    		

    		$page = $request->request->get('page',1);
    		
    		$paginator  = $this->get('knp_paginator');
    		$pagination = $paginator->paginate(
    				$cached_data,
    				$page/*page number*/,
    				5/*limit per page*/
    		);
    		 
    		$content =  explode("<<||>>", $this->get('twig')
    											->render('InterArticleBundle:Admin:_articleListPagingAjax.html.twig',
    											array('pagination' => $pagination,    						
    				)));
    		//$return=json_encode(array('id' => $id, 'role'=> $role, 'result' => '1'));
    		$return = json_encode(array(
    						'list'=>$content[0],
    						'paging'=>$content[1]
    		));
    		return new Response($return,200,array('Content-Type'=>'application/json'));
    		//return new JsonResponse(array('id' => $id, 'role'=> $role, 'result' => '1'));
    	}
    	return new Response('This is not ajax!', 400);
    }
    
}

?>